package com.zlzlib.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @DateTime: 2023/3/7 9:34
 * @Author zlz
 * @Version 1.0
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    /**
     * 上下文环境
     */
    private static ApplicationContext applicationContext;


    /**
     * 容器是否初始化
     *
     * @return true=已经初始化
     */
    public static boolean isInit() {
        return applicationContext != null;
    }


    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * 获取对象
     */
    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据注解获取bean
     */
    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException {
        return applicationContext.getBeansWithAnnotation(annotationType);
    }

    /**
     * 根据注解获取bean
     */
    public static <T> Map<String, T> getBeansOfType(Class<T> annotationType) throws BeansException {
        return applicationContext.getBeansOfType(annotationType);
    }
}